import 'package:dio/dio.dart';
import 'package:practise/arch/http/interceptor/log_interceptor.dart';

typedef JsonParser<T> = T Function(Map<String, dynamic> data);

//TODO 请求封装成Request类模式
class Engine {

  static const _TIMEOUT_SECONDS = 10 * 1000;

  Engine._internal();

  static Engine _sInstance;

  static Engine getInstance() {
    if (_sInstance == null) {
      _sInstance = Engine._internal();
    }
    return _sInstance;
  }

  Dio _dio;

  Dio _getDio() {
    if (_dio == null) {
      _dio = Dio();
      _dio.options = _getDefaultOptions();
      _dio.interceptors.add(HttpLogInterceptor());
    }
    return _dio;
  }

  BaseOptions _getDefaultOptions() {
    final options = BaseOptions();
    options.baseUrl = "https://www.wanandroid.com";
    options.method = 'GET';
    options.responseType = ResponseType.json;
    options.connectTimeout = _TIMEOUT_SECONDS;
    options.receiveTimeout = _TIMEOUT_SECONDS;
    options.sendTimeout = _TIMEOUT_SECONDS;
    return options;
  }

  Future<T> get<T>(String path, {JsonParser<T> parser, Map<String, dynamic> queryParameters, Options options}) {
    return _request('GET', path, parser, queryParameters, null, options);
  }

  Future<T> post<T>(String path, {JsonParser<T> parser, data, Options options}) {
    return _request('POST', path, parser, null, data, options);
  }

  Future<T> _request<T>(String method, String path, JsonParser<T> parser,
      Map<String, dynamic> queryParameters, data, Options options) async {
    method = method ?? 'GET';
    options = options ?? Options();
    options.method = method;
    return await _getDio()
        .request(path, data: data, queryParameters: queryParameters, options: options)
        .then((value) {
          if (parser != null) {
            return parser.call(value.data);
          } else {
            return value.data;
          }
    });
  }
}
